<template>
  <div class="post-container">
    <el-button type="primary" @click="openDialog()">新增</el-button>
    <el-input v-model="postName" placeholder="请输入职位名称" clearable style="width: 200px" />
    <el-button type="button" @click="fetchPostList(true)">搜索</el-button>
    <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
        element-loading-text="数据加载中..."
    >
      <!-- 所有列定义 -->
      <el-table-column prop="postId" label="ID" width="80" align="center" />
      <el-table-column prop="postName" label="职位名称" width="150" />
      <el-table-column prop="postSort" label="排序" width="80" align="center" />
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="{row}">
          <el-tag :type="row.status === '0' ? 'success' : 'danger'" size="small">
            {{ row.status === '0' ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createBy" label="创建人" width="120" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column prop="flag" label="标志" width="80" align="center">
        <template #default="{row}">
          <el-tag :type="row.flag ? 'success' : 'info'" size="small">
            {{ row.flag ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <template #default="{row}">
          <el-button
              type="primary"
              size="mini"
              @click="openDialog(row)"
              icon="el-icon-edit"
          >编辑</el-button>
          <el-button
              type="danger"
              size="mini"
              @click="handleDelete(row)"
              icon="el-icon-delete"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹框 -->
    <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="500px"
    >
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="职位名称" prop="postName">
          <el-input v-model="formData.postName" />
        </el-form-item>
        <el-form-item label="岗位编码" prop="postCode" :rules="rules">
          <el-input v-model="formData.postCode" />
        </el-form-item>
        <el-form-item label="岗位顺序" prop="postSort">
          <el-input-number
              v-model="formData.postSort"
              :min="0"
              :max="9999"
              :step="1"
          />
        </el-form-item>
        <el-form-item label="岗位状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 分页组件 -->
    <el-pagination
        class="pagination-wrapper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.pageNum"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    />
  </div>
</template>
<script>
import {getPostList, addPostFn, editPutFn,deletePostFn,searchPostFn} from '@/api/postManager';

export default {
  name: 'PostList',
  data() {
    return {
      loading: false,
      tableData: [],
      total: 0,
      pagination: {
        pageNum: 1,
        pageSize: 10
      },
      postName: '',
      dialogVisible: false,
      dialogTitle: '', // 新增字段用于存储弹框标题
      formData: {
        postId: null,
        postName: '',
        postSort: '',
        postCode:'',
        status: '0',
        flag: '0'
      },
      rules: {
        postName: [{ required: true, message: '请输入职位名称', trigger: 'blur' }],
        postSort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }]
      }
    };
  },
  created() {
    this.fetchPostList();
  },
  methods: {
    //删除
    async handleDelete(row) {
      this.$confirm('是否删除该数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
          .then(async () => {
            try {
              const response = await deletePostFn(row.postId);
              const res = response.data;

              if (res.code === 200) {
                this.$message.success('删除成功');
                this.fetchPostList();
              }
            }
            catch (error) {
              console.error('请求失败:', error);
              this.$message.error('请求失败: ')
            }
          })
    },

    async fetchPostList(isSearch = false) {
      this.loading = true;
      try {
        let response;
        const params = { ...this.pagination, postName: this.postName };
     
        if (isSearch) {
          response = await searchPostFn(params);
        } else {
          response = await getPostList(this.pagination);
        }
        const res = response.data;
        console.log('接口返回的数据:', res);
        if (res.code === 200) {
          this.tableData = res.rows;
          this.total = res.total;
        } else {
          this.$message.error(res.msg || '获取数据失败');
        }
      } catch (error) {
        console.error('请求失败:', error);
        this.$message.error('请求失败: ' + (error.message || '未知错误'));
      } finally {
        this.loading = false;
      }
    },

    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.fetchPostList();
    },
    handleCurrentChange(val) {
      this.pagination.pageNum = val;
      this.fetchPostList();
    },
    openDialog(row = null) {
      if (row) {
        this.formData = { ...row }; // 编辑时回显数据
        this.dialogTitle = '修改岗位'; // 设置编辑时的标题
      } else {
        this.formData = {
          postId: null,
          postName: '',
          postSort: '',
          status: '0',
          flag: '0'
        }; // 新增时清空表单
        this.dialogTitle = '添加岗位'; // 设置新增时的标题
      }
      this.dialogVisible = true;
    },
    //确定
    async handleSubmit() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          console.log(this.formData);
          // 确保 postSort 是数字类型
          this.formData.postSort = parseInt(this.formData.postSort, 10);
          console.log(this.formData);
          try {
            if (this.formData.postId) {
              await editPutFn(this.formData);
              this.$message.success('编辑成功');
            } else {
              await addPostFn(this.formData);
              this.$message.success('新增成功');
            }
            this.dialogVisible = false;
            this.fetchPostList();
          } catch (error) {
            console.error('操作失败:', error);
            this.$message.error('操作失败: ' + (error.message || '未知错误'));
          }
        }
      });
    }

  }
};
</script>
<style scoped>
.post-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.el-table {
  margin-top: 20px;
}
</style>



